package com.studyweb.controller;

import com.studyweb.pojo.vo.Result;
import com.studyweb.pojo.entity.WrongQuestion;
import com.studyweb.service.WrongQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 错题本控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/wrong-question")
public class WrongQuestionController {
    
    @Autowired
    private WrongQuestionService wrongQuestionService;
    
    /**
     * 获取错题列表
     */
    @GetMapping("/questions")
    public Result getQuestions(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String questionType,
            @RequestParam(required = false) String difficulty,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = wrongQuestionService.getQuestions(pageNum, pageSize, questionType, difficulty, category, module, keyword);
            return Result.success("获取错题列表成功", result);
        } catch (Exception e) {
            log.error("获取错题列表异常：{}", e.getMessage(), e);
            return Result.error("获取错题列表失败");
        }
    }
    
    /**
     * 创建错题记录
     */
    @PostMapping("/questions")
    public Result createQuestion(@Valid @RequestBody WrongQuestion question, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            question.setUserId(userId);
            boolean success = wrongQuestionService.createQuestion(question);
            if (success) {
                return Result.success("创建错题成功");
            } else {
                return Result.error("创建错题失败");
            }
        } catch (Exception e) {
            log.error("创建错题异常：{}", e.getMessage(), e);
            return Result.error("创建错题失败");
        }
    }
    
    /**
     * 获取错题详情
     */
    @GetMapping("/questions/{id}")
    public Result getQuestion(@PathVariable Long id) {
        try {
            WrongQuestion question = wrongQuestionService.getQuestionById(id);
            if (question != null) {
                return Result.success("获取错题详情成功", question);
            } else {
                return Result.error("错题不存在");
            }
        } catch (Exception e) {
            log.error("获取错题详情异常：{}", e.getMessage(), e);
            return Result.error("获取错题详情失败");
        }
    }
    
    /**
     * 更新错题
     */
    @PutMapping("/questions/{id}")
    public Result updateQuestion(@PathVariable Long id, @Valid @RequestBody WrongQuestion question) {
        try {
            question.setQuestionId(id);
            boolean success = wrongQuestionService.updateQuestion(question);
            if (success) {
                return Result.success("更新错题成功");
            } else {
                return Result.error("更新错题失败");
            }
        } catch (Exception e) {
            log.error("更新错题异常：{}", e.getMessage(), e);
            return Result.error("更新错题失败");
        }
    }
    
    /**
     * 删除错题
     */
    @DeleteMapping("/questions/{id}")
    public Result deleteQuestion(@PathVariable Long id) {
        try {
            boolean success = wrongQuestionService.deleteQuestion(id);
            if (success) {
                return Result.success("删除错题成功");
            } else {
                return Result.error("删除错题失败");
            }
        } catch (Exception e) {
            log.error("删除错题异常：{}", e.getMessage(), e);
            return Result.error("删除错题失败");
        }
    }
    
    /**
     * 批量删除错题
     */
    @DeleteMapping("/questions/batch")
    public Result batchDeleteQuestions(@RequestBody List<Long> ids) {
        try {
            boolean success = wrongQuestionService.batchDeleteQuestions(ids);
            if (success) {
                return Result.success("批量删除错题成功");
            } else {
                return Result.error("批量删除错题失败");
            }
        } catch (Exception e) {
            log.error("批量删除错题异常：{}", e.getMessage(), e);
            return Result.error("批量删除错题失败");
        }
    }
    
    /**
     * 获取练习题目
     */
    @GetMapping("/practice")
    public Result getPracticeQuestions(
            @RequestParam(required = false) Integer count,
            @RequestParam(required = false) String difficulty,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String orderBy,
            @RequestParam(required = false) String orderType) {
        try {
            log.info("获取练习题目参数: count={}, difficulty={}, category={}, module={}, orderBy={}, orderType={}", count, difficulty, category, module, orderBy, orderType);
            List<WrongQuestion> questions = wrongQuestionService.getPracticeQuestions(count, difficulty, category, module, orderBy, orderType);
            return Result.success("获取练习题目成功", questions);
        } catch (Exception e) {
            log.error("获取练习题目异常：{}", e.getMessage(), e);
            return Result.error("获取练习题目失败");
        }
    }
    
    /**
     * 提交答案
     */
    @PostMapping("/submit")
    public Result submitAnswer(@RequestBody Map<String, Object> answerData) {
        try {
            Map<String, Object> result = wrongQuestionService.submitAnswer(answerData);
            return Result.success("提交答案成功", result);
        } catch (Exception e) {
            log.error("提交答案异常：{}", e.getMessage(), e);
            return Result.error("提交答案失败");
        }
    }
    
    /**
     * 获取答题结果
     */
    @GetMapping("/results")
    public Result getResults(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = wrongQuestionService.getResults(pageNum, pageSize);
            return Result.success("获取答题结果成功", result);
        } catch (Exception e) {
            log.error("获取答题结果异常：{}", e.getMessage(), e);
            return Result.error("获取答题结果失败");
        }
    }
}